<template>
  <div>
    <hs-breadcrumb :breadcrumb="breadcrumb"></hs-breadcrumb>
    <Card :bordered="false" :style="{ marginBottom: '10px' }">
      <div class="hs-screen-row">
        <Input
          v-model="params.mobile"
          placeholder="门店名称"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <Input
          v-model="params.code"
          placeholder="联系电话"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <Input
          v-model="params.code"
          placeholder="运营人员"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <DatePicker
          @on-change="changeDate"
          v-model="dateInit2"
          type="daterange"
          :editable="false"
          separator=" ~ "
          split-panels
          transfer
          placeholder="创建时间"
          style="width: 200px"
        ></DatePicker>
      </div>
      <div class="hs-screen-row">
        <Button type="primary" @click="findOrderMallList">查询</Button>
      </div>
      <div class="hs-screen-row">
        <Button @click="resetScreen">重置</Button>
      </div>
    </Card>

    <Card :bordered="false" :style="{ marginBottom: '10px' }">
      <!--标题-->
      <div slot="title">
        <div class="hs-screen-box">
          <div>订单列表</div>
          <div>
            <ButtonGroup>
              <!-- <Button @click="cancatOrder" type="success">合并订单</Button> -->
              <Button @click="addHandle">新增</Button>
              <Button @click="findOrderMallList">
                <Icon type="md-refresh" size="15" />
              </Button>
            </ButtonGroup>
          </div>
        </div>
      </div>
      <!--表格数据-->
      <Table
        :columns="columns"
        :data="data"
        size="small"
        :stripe="true"
        :loading="isTableLoading"
        ref="tableRef"
        @on-select="selectTable"
        @on-select-cancel="selectCancelTable"
        @on-select-all="selectAllTable"
        @on-select-all-cancel="selectAllCancelTable"
      >
        <template slot="area" slot-scope="{ row }">
          {{ `${row.province || ''}${row.city || ''}${row.district || ''}` }}
        </template>
        <template slot-scope="{ row }" slot="action">
          <Button
            type="success"
            size="small"
            style="margin-right: 5px"
            @click="viewOrderOpe(row)"
          >
            查看
          </Button>
          <Button
            type="warning"
            size="small"
            style="margin-right: 5px"
            @click="editOrderOpe(row)"
          >
            编辑
          </Button>
        </template>
      </Table>
      <!--分页-->
      <div class="hs-page">
        <Page
          :total="total"
          show-sizer
          show-total
          transfer
          @on-change="changePage"
          @on-page-size-change="changePageSize"
        />
      </div>
    </Card>
    <StoreOpe ref="storeOpeRef" @changeData="changeDataHandle" />
  </div>
</template>

<script>
  import hsBreadcrumb from '@/components/hs-breadcrumb';
  import { ORDER_STATE_LIST } from '@/constant/order.js';
  import { platformList } from '@/constant/program';
  import StoreOpe from './components/store-management-ope.vue';
  import { get } from 'lodash';
  export default {
    name: 'admin',
    data() {
      return {
        ORDER_STATE_LIST,
        total: 0,
        importSuccess: 0,
        importFailed: 0,
        dateInit: '',
        dateInit2: '',
        isTableLoading: false,
        isShowImport: false,
        // 选中数据
        selectData: [],
        action: this.$apiURL + '/orderMall/importOrderExcel',
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        showConcat: false,
        formInline: {
          fromCodes: '',
          toCode: ''
        },
        ruleInline: {
          fromCodes: [
            { required: true, message: '请输入订单编号', trigger: 'blur' }
          ],
          toCode: [
            {
              required: true,
              message: '请输入合并后的订单编号',
              trigger: 'blur'
            }
          ]
        },
        // 参数
        params: {
          page: 1,
          rows: 10
        },
        // 表格列
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '门店名称',
            minWidth: 120,
            key: 'name'
          },
          {
            title: '经营者',
            minWidth: 190,
            key: 'managerName'
          },
          {
            title: '联系电话',
            minWidth: 120,
            key: 'managerPhone'
          },
          {
            title: '地区',
            minWidth: 120,
            slot: 'area'
          },
          {
            title: '运营人员',
            minWidth: 120,
            key: 'operation'
          },
          {
            title: '创建时间',
            minWidth: 120,
            key: 'createTime'
          },
          {
            title: '操作',
            slot: 'action',
            minWidth: 220,
            align: 'center'
          }
        ],
        // 表格数据
        data: [],
        failOrderData: [],
        // 面包屑
        breadcrumb: [
          { name: '首页', url: '', icon: 'ios-home-outline', size: 18 },
          { name: '系统管理', url: '', icon: '', size: 0 },
          { name: '订单列表', url: '', icon: '', size: 0 }
        ]
      };
    },
    created() {
      // 订单-列表查询
      this.findOrderMallList();
    },
    methods: {
      changeDataHandle() {
        this.findOrderMallList();
      },
      confirmConcatHandle() {
        if (this.formInline.fromCodes.indexOf(this.formInline.toCode) < 0) {
          this.$Message.error('合并后的订单必须属于合并订单中的一个!');
          return;
        }

        this.$refs['formInline'].validate(valid => {
          if (valid) {
            this.axios
              .get('/orderMall/mergeOrder', {
                params: this.formInline
              })
              .then(() => {
                this.$Message.success('合并成功');
                this.formInline = {
                  fromCodes: '',
                  toCode: ''
                };
              });
          } else {
            this.$Message.error('请输入正确信息!');
          }
        });
      },
      cancatOrder() {
        this.showConcat = true;
      },
      pushFactoryHandle(row) {
        this.axios
          .get('/orderMall/pushOrderToFactory', {
            params: { orderCode: row.mallOrderCode }
          })
          .then(() => {
            this.$Message.success('推送成功');
          });
      },
      exportHandle() {
        console.log(this.params);
        this.exportExcel();
      },
      viewWarnOrder(row) {
        this.$refs.orderViewerRef.show(row, false);
      },
      cancelHandle(row) {
        this.$Modal.confirm({
          title: `撤销后，用户可使用本券码进行退款或再次核销。`,
          onOk: () => {
            let cancelApi = '';
            if (row.plantType == 1) {
              // 快手
              cancelApi = this.axios.get('/voucher/v1/cancelVerify', {
                params: { id: row.voucherId }
              });
            } else if (row.plantType == 2) {
              // 美团
              cancelApi = this.axios.get('/orderMall/cancelVerify', {
                params: { orderCode: row.mallOrderCode }
              });
            } else if (row.plantType == 3) {
              // 抖音
              cancelApi = this.axios.get('/orderMall/dyCancelVerify', {
                params: { orderCode: row.mallOrderCode }
              });
            }

            if (!cancelApi) {
              this.$Notice.error({
                title: '撤销失败',
                desc: '暂不支持此平台',
                duration: 3
              });
              return;
            }

            cancelApi.then(res => {
              if (res.status != 200) {
                this.$Notice.error({
                  title: '撤销失败',
                  desc: res.msg,
                  duration: 3
                });
              } else {
                this.$Notice.success({
                  title: '撤销成功',
                  desc: '撤销成功',
                  duration: 3
                });
                this.findOrderMallList();
              }
            });
          },
          onCancel: () => {
            this.$Message.info('您点击了取消.');
          }
        });
      },
      // 订单-列表查询
      findOrderMallList() {
        this.isTableLoading = true;
        this.axios.post('/shopinfo/findList', { ...this.params }).then(res => {
          this.isTableLoading = false;
          if (res.status == 200) {
            this.total = res.data.total;
            this.data = res.data.rows;
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '查询订单列表接口报错',
              duration: 0
            });
          }
        });
      },
      addHandle() {
        this.$refs.storeOpeRef.show(2);
      },
      viewOrderOpe(row) {
        this.$refs.storeOpeRef.show(1, row);
      },
      editOrderOpe(row) {
        this.$refs.storeOpeRef.show(3, row);
      },
      // 是否取消订单
      isOrderCancel(row) {
        this.$Modal.confirm({
          title: `是否取消当前订单？`,
          onOk: () => {
            // this.$Message.info('您点击了确定.');
            this.orderCancel(row);
          },
          onCancel: () => {
            this.$Message.info('您点击了取消.');
          }
        });
      },
      // 是否删除订单
      isDeleteOrderMall(row) {
        // console.log(row)
        this.$Modal.confirm({
          title: `是否删除当前订单？`,
          onOk: () => {
            // this.$Message.info('您点击了确定.');
            this.deleteOrderMall(row);
          },
          onCancel: () => {
            this.$Message.info('您点击了取消.');
          }
        });
      },
      // 取消订单
      orderCancel(row) {
        this.$Spin.show();
        this.axios
          .post('/orderMall/orderCancel', {
            mallOrderId: row.mallOrderId
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.$Message.success('操作成功.');
              this.findOrderMallList();
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '取消订单接口报错',
                duration: 0
              });
            }
          });
      },
      // 删除订单
      deleteOrderMall(row) {
        this.$Spin.show();
        this.axios
          .post('/orderMall/deleteOrderMall', {
            mallOrderId: row.mallOrderId
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.$Message.success('操作成功.');
              this.findOrderMallList();
            }
            if (res.status == 201) {
              // this.$Message.error(res.msg);
              this.$Notice.error({
                title: '删除订单失败',
                desc: res.msg
              });
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '删除订单接口报错',
                duration: 0
              });
            }
          });
      },
      // 导出订单Excel
      exportExcel() {
        this.$Spin.show();
        this.axios
          .post('/orderMall/export', this.params, {
            responseType: 'arraybuffer'
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            // console.log(res);
            let blob = new Blob([res], { type: 'Files' });
            let csvUrl = URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.href = csvUrl;
            // 下载xlsx文件
            link.download = `${this.params.factoryCode || '全部订单'}${
              this.params.takeStartTime
            }~${this.params.takeEndTime}.xlsx`;
            link.click();
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '删除订单接口报错',
                duration: 0
              });
            }
          });
      },
      // 显示操作模态框
      showOrderOpe(row) {
        this.$refs.orderOpe.show(row);
      },
      showUpdateBackInfo(row) {
        this.$refs.backInfo.show(row);
      },
      // 显示物流跟踪
      showOrderLogisticsTracking(row) {
        this.$refs.orderLogisticsTracking.show(row);
      },
      // 发货，修改物流信息
      showOrderLogisticsNumber(row, type) {
        this.$refs.orderLogisticsNumber.show(row, type);
      },
      // 显示自定义退款页面
      showOrderCustomRefund(row, type) {
        this.$refs.orderCustomRefund.show(row, type);
      },
      // 日期条件赋值
      changeDate(e) {
        this.params.successTimeStart = e[0];
        this.params.successTimeEnd = e[1];
      },
      changeDate2(e) {
        this.params.takeStartTime = e[0];
        this.params.takeEndTime = e[1];
      },
      // 重置筛选条件
      resetScreen() {
        this.params.mallOrderCode = '';
        this.params.orderState = '';
        this.params.nickName = '';
        this.params.mobile = '';
        this.params.consigneeName = '';
        this.params.consigneePhone = '';
        this.params.successTimeStart = '';
        this.params.successTimeEnd = '';
        this.params.code = '';
        this.params.mallOrderCode = '';
        this.params.poiName = '';
        this.dateInit = '';
        this.dateInit2 = '';
        this.findOrderMallList();
      },
      // 改变页数
      changePage(e) {
        this.params.page = e;
        this.findOrderMallList();
      },
      // 改变页容量
      changePageSize(e) {
        this.params.rows = e;
        this.findOrderMallList();
      },
      // 在多选模式下有效，选中某一项时触发
      selectTable(selection, row) {
        console.log(selection, this.$refs.tableRef);
        this.selectData = selection;
      },
      // 在多选模式下有效，取消选中某一项时触发
      selectCancelTable(selection, row) {
        this.selectData = selection;
      },
      // 在多选模式下有效，点击全选时触发
      selectAllTable(selection) {
        this.selectData = selection;
      },
      // 在多选模式下有效，点击取消全选时触发
      selectAllCancelTable(selection) {
        this.selectData = selection;
      }
    },
    computed: {
      plantTypeText() {
        return plantType => {
          const plantTypeItem = platformList.find(
            item => item.value == plantType
          );
          return get(plantTypeItem, 'label', '');
        };
      },

      showUpadeBackInfo() {
        return this.$store.state.userInfo.roleName.indexOf('修改订单信息') >= 0;
      }
    },
    components: {
      hsBreadcrumb,
      StoreOpe
    }
  };
</script>

<style scoped lang="less">
  .hs-upload-image-box {
    width: 485px;
    display: flex;
    align-items: center;
    justify-content: center;

    .hs-upload-add {
      cursor: pointer;
      width: 100%;
      height: 43px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #cccccc;
      transition: all 0.3s;

      &:hover {
        color: #2d8cf0;
        border: 1px dashed #2d8cf0;
      }
    }
  }
  .z-import-message {
    margin: 10px 0;
  }
</style>
